//
//  FaceScanViewController.m
//  FaceDiscernmentDemo
//
//  Created by mac on 2019/2/20.
//  Copyright © 2019年 mac. All rights reserved.
//

#import "FaceScanViewController.h"

@interface FaceScanViewController ()

@property (nonatomic,readwrite,retain) UIView *animaView;
@property (nonatomic,strong) FaceInfo *faceinfo;
@property (nonatomic,strong) NSDictionary *faceImagesDict;
@property (nonatomic,strong) NSString *encodedImageStr;

@end

@implementation FaceScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //看Demo上的作用是为做闪屏幕动画之用
    self.animaView = [[UIView alloc]initWithFrame:self.view.bounds];
    self.animaView.backgroundColor = [UIColor whiteColor];
    self.animaView.alpha = 0;
    [self.view addSubview:self.animaView];
    
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[IDLFaceDetectionManager sharedInstance] startInitial];//进入界面则开始
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [IDLFaceDetectionManager.sharedInstance reset];//重置处理
}

- (void)onAppWillResignAction {
    [super onAppWillResignAction];
    [IDLFaceDetectionManager.sharedInstance reset];
}



//获取人脸图片信息
- (void)faceProcesss:(UIImage *)image{
    if (self.hasFinished) {//判断是否请求成功
        return;
    }
    __weak typeof(self) weakSelf = self;
    
    //人脸图像检测 人脸识别
    NSInteger num = 0;
    NSArray *faceRectsAyy = [NSArray array];//人脸特征点

    [[FaceSDK sharedInstance]detectFaceInImage:image withMethodType:FaceSDKDetectMethodType_NIR andGetFaceRects:&faceRectsAyy andFaceNumber:&num andMinimumFaceSize:200];
    CGRect rect = [faceRectsAyy.firstObject CGRectValue];
    
    //人脸精准对齐
    [[FaceSDK sharedInstance]fineAlignFaceInImage:image withMethodType:FaceSDKMethodTypeCDNN andFaceShape:&faceRectsAyy andNumOfPoints:72];
    
    //人脸追踪
    CGFloat numfloat = 0.9;
    [[FaceSDK sharedInstance]trackFaceInImage:image withMethodType:FaceSDKMethodTypeCDNN andFaceShape:&faceRectsAyy andNumOfPoints:72 andScore:&numfloat];
    
    //人脸姿态获取
    NSInteger rowNum = 200;
    NSInteger columNum = 200;
    [[FaceSDK sharedInstance]headPostEstimationWithFaceShape:faceRectsAyy andImgDataRowNum:rowNum andImgColumNum:columNum andNumOfPoints:72];
    
    //人脸姿态获取(常用方法)
    [[FaceSDK sharedInstance]headPostEstimationWithImage:image andFaceShape:faceRectsAyy andNumOfPoints:72];
    
    //多人脸追踪
    [[FaceVerifier sharedInstance]trackWithImage:image andMaxFaceCount:num];
    
    //人脸追踪识别
    [[FaceVerifier sharedInstance]prepareDataWithImage:image andActionType:FaceVerifierActionTypeRecognition];
    
    //最大人脸追踪识别
    [[FaceVerifier sharedInstance]prepareDataForMaxFaceWithImage:image andActionType:FaceVerifierActionTypeRecognition];
    
    //人脸图片质量检测
    NSArray *marks = self.faceinfo.landMarks;
    if (marks.count>0) {
        CGFloat blurinessFloat = 0;//模糊
        NSInteger illumFloat = 0;//光照
        NSInteger nOccluPart = 0;//人脸遮挡部位数量
        NSArray *occlu = [NSArray array];
        [[FaceVerifier sharedInstance]imageQualityWith:image andFaceShape:&marks andNumOfPoints:marks.count bluriness:&blurinessFloat illum:&illumFloat occlusion:&occlu nOccluPart:&nOccluPart];
    }
    
    //人脸抠图
    //output抠图结果图片特征点
    UIImage *cropImage = [[UIImage alloc]init];
    NSArray *cropShapsArray = [NSArray array];
    NSArray *faceShapes = self.faceinfo.landMarks;
    [[FaceVerifier sharedInstance]cropFaceImageWith:image FaceShape:&faceShapes numOfPoints:faceShapes.count faceImageWidth:200 faceImageHeight:200 cropImage:&cropImage cropShaps:&cropShapsArray];
    
    /*多人脸追踪*/
//    [[IDLFaceDetectionManager sharedInstance]detectMultiFacesImage:image withMaxFaceCount:2 handler:^(FaceInfo *faceinfo, TrackDetectRemindCode remindCode) {
//        switch (remindCode) {
//            case TrackDetectRemindCodeOK:{
//                //请求成功
//                [self warningStatus:PoseStatus warning:@"成功"];
//                break;
//            }
//            case TrackDetectRemindCodeImageBlured:{
//                [self warningStatus:PoseStatus warning:@"图像模糊"];
//            }
//
//            default:
//                break;
//        }
//    }];
    
    /*不带黑边的方法*/
//    [[IDLFaceDetectionManager sharedInstance]detectStratrgyWithNormalImage:image previewRect:self.previewRect detectRect:self.detectRect completionHandler:^(FaceInfo *faceinfo, NSDictionary *images, DetectRemindCode remindCode) {
//
//    }];
    
    
    /*不论带不带黑边，取图片都是：images[@"bestImage"]*/
    //带黑边的方法
    [[IDLFaceDetectionManager sharedInstance]detectStratrgyWithQualityControlImage:image previewRect:self.previewRect detectRect:self.detectRect completionHandler:^(FaceInfo *faceinfo, NSDictionary *images, DetectRemindCode remindCode) {
        self.faceImagesDict = [[NSDictionary alloc]initWithDictionary:images];
        switch (remindCode) {
            case DetectRemindCodeOK:
            {
                //请求成功的方法
                weakSelf.hasFinished = YES;
                [self warningStatus:CommonStatus warning:@"非常好"];
                if (images[@"bestImage"] !=nil && [images[@"bestImage"]count] !=0) {
                    NSData *data = [[NSData alloc]initWithBase64EncodedString:[images[@"bestImage"] lastObject] options:NSDataBase64DecodingIgnoreUnknownCharacters];
                    UIImage *bestImage = [UIImage imageWithData:data];
                    //输出查看image信息
                    NSLog(@"bestImage=%@",bestImage);
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [UIView animateWithDuration:0.5 animations:^{
                        weakSelf.animaView.alpha = 1;
                    } completion:^(BOOL finished) {
                        [UIView animateWithDuration:0.5 animations:^{
                            weakSelf.animaView.alpha = 0;
                        } completion:^(BOOL finished) {
                            [weakSelf closeAction];//调取结束的方法
                        }];
                    }];
                });
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (weakSelf.successCompletion) {
                        weakSelf.successCompletion(images, image);
                    }
                });
                //将请求成功的状态传出
                [self singleActionSuccess:true];
                break;
            }
            case DetectRemindCodePitchOutofDownRange:
                [self warningStatus:PoseStatus warning:@"建议略微抬头"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodePitchOutofUpRange:
                [self warningStatus:PoseStatus warning:@"建议略微低头"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeYawOutofLeftRange:
                [self warningStatus:PoseStatus warning:@"建议略微向右转头"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeYawOutofRightRange:
                [self warningStatus:PoseStatus warning:@"建议略微向左转头"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodePoorIllumination:
                [self warningStatus:CommonStatus warning:@"光线再亮些"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeNoFaceDetected:
                [self warningStatus:CommonStatus warning:@"把脸移入框内"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeImageBlured:
                [self warningStatus:CommonStatus warning:@"请保持不动"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionLeftEye:
                [self warningStatus:occlusionStatus warning:@"左眼有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionRightEye:
                [self warningStatus:occlusionStatus warning:@"右眼有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionNose:
                [self warningStatus:occlusionStatus warning:@"鼻子有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionMouth:
                [self warningStatus:occlusionStatus warning:@"嘴巴有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionLeftContour:
                [self warningStatus:occlusionStatus warning:@"左脸颊有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionRightContour:
                [self warningStatus:occlusionStatus warning:@"右脸颊有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeOcclusionChinCoutour:
                [self warningStatus:occlusionStatus warning:@"下颚有遮挡"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeTooClose:
                [self warningStatus:CommonStatus warning:@"手机拿远一点"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeTooFar:
                [self warningStatus:CommonStatus warning:@"手机拿近一点"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeBeyondPreviewFrame:
                [self warningStatus:CommonStatus warning:@"把脸移入框内"];
                [self singleActionSuccess:false];
                break;
            case DetectRemindCodeVerifyInitError:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyDecryptError:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyInfoFormatError:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyExpired:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyMissRequiredInfo:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyInfoCheckError:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyLocalFileError:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeVerifyRemoteDataError:
                [self warningStatus:CommonStatus warning:@"验证失败"];
                break;
            case DetectRemindCodeTimeout:{
                //请求超时
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"remind提醒" message:@"已超时" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"好的，我将从新请求" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alertController addAction:action];
                    UIViewController *fatherViewController = weakSelf.presentingViewController;
                    [weakSelf dismissViewControllerAnimated:YES completion:^{
                        [fatherViewController presentViewController:alertController animated:YES completion:nil];
                    }];
                });
                break;
            }
            case DetectRemindCodeConditionMeet:{
                //满足条件提醒码
                self.circleView.conditionStatusFit = true;
            }
                
            default:
                break;
        }
        if (remindCode == DetectRemindCodeConditionMeet || remindCode == DetectRemindCodeOK) {
            self.circleView.conditionStatusFit = true;
        }else {
            self.circleView.conditionStatusFit = false;
        }
    }];
    
//    NSLog(@"faceImages == %@",self.faceImagesDict);
    NSTimeInterval start = [[NSDate date] timeIntervalSince1970];
    int userId_start = start;
    if ([_faceImagesDict count]) {
        
        NSData *data = UIImageJPEGRepresentation(image, 1.0f);
        _encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
////        NSLog(@"encodedImageStr=%@",encodedImageStr);
        [self setFaceverify];//活体检测
//        //人脸注册
//        NSDictionary *parm = @{@"access_token":[FaceAppToolHandle shareToolHandle].accessToken,@"image":_encodedImageStr,@"image_type":@"BASE64",@"group_id":@"6",@"user_id":[NSString stringWithFormat:@"%i",userId_start],@"user_info":[NSString stringWithFormat:@"%f",start],@"quality_control":@"LOW",@"liveness_control":@"LOW"};
//        [WebConnect webPOSTConnectWithWithStrUrl:Baidu_getFacesetUserAddURL pramaters:parm success:^(id responseObject) {
//            NSLog(@"人脸注册==%@",responseObject);
//            [self setFaceseDetect];
//        } failure:^(id failure) {
//            NSLog(@"失败=%@",failure);
//        }];
        
    }
}
//在线活体检测
- (void)setFaceverify{
    NSArray *parm = @[@{@"access_token":[FaceAppToolHandle shareToolHandle].accessToken,@"image":_encodedImageStr,@"image_type":@"BASE64"}];
    [WebConnect postDataWithPath:[NSString stringWithFormat:@"%@?access_token=%@",Baidu_getFaceSetFaceverifyURL,[FaceAppToolHandle shareToolHandle].accessToken] parameters:parm completion:^(NSError *error, id resultObject) {
        if (error == nil) {
            NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"在线活体检测 = %@",dict);
        } else {
            NSLog(@"失败=%@",error);
        }
    }];
    
}

//人脸搜索-M:N识别
- (void)setFaceSearch{
//    Baidu_getFaceSetMulti_SearchURL
    [WebConnect webPOSTConnectWithWithStrUrl:Baidu_getFaceSetMulti_SearchURL pramaters:nil success:^(id responseObject) {
        NSLog(@"人脸搜索-M:N识别=%@",responseObject);
    } failure:^(id failure) {
        NSLog(@"失败=%@",failure);
    }];
}

//人脸检测接口
- (void)setFaceseDetect{
    NSDictionary *parm = @{@"access_token":[FaceAppToolHandle shareToolHandle].accessToken,@"image":_encodedImageStr,@"image_type":@"BASE64",@"face_field":@"ge,beauty,expression,faceshape,gender,glasses,landmark,race,quality",@"max_face_num":@"1",@"face_type":@"LIVE"};
    [WebConnect webPOSTConnectWithWithStrUrl:Baidu_getFacesetDetectURL pramaters:parm success:^(id responseObject) {
        NSLog(@"人脸检测==%@",responseObject);
        [self setFaceSetSearch];
    } failure:^(id failure) {
        NSLog(@"失败=%@",failure);
    }];
}
//人脸搜索
- (void)setFaceSetSearch{
    NSDictionary *parm = @{@"access_token":[FaceAppToolHandle shareToolHandle].accessToken,@"image":_encodedImageStr,@"image_type":@"BASE64",@"group_id_list":@"0,1,2,3,4,5,6,7,8,9",@"quality_control":@"LOW",@"liveness_control":@"LOW"};
    [WebConnect webPOSTConnectWithWithStrUrl:Baidu_getFacesetSearchURL pramaters:parm success:^(id responseObject) {
        NSLog(@"人脸搜索==%@",responseObject);
    } failure:^(id failure) {
        NSLog(@"失败=%@",failure);
    }];
    
}

- (void)dealloc
{
    
}



@end
